package server;

import org.dom4j.Document;
import org.dom4j.DocumentException;
import org.dom4j.Element;
import org.dom4j.io.SAXReader;
import server.classloader.MyClassLoader;
import server.config.Context;
import server.config.Host;

import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.net.ServerSocket;
import java.net.Socket;
import java.net.URL;
import java.net.URLClassLoader;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;
import java.util.concurrent.*;

/**
 * Minicat主类
 *
 * @author 陶肖寅
 * @version V1.0
 * @Package server
 * @date 2020-02-24 10:52
 * @Copyright © 2020-2021 城云科技(中国)有限公司
 */
public class Bootstrap {
    /**
     * 定义socket监听端口号
     */
    private int port;

    public int getPort() {
        return port;
    }

    public void setPort(int port) {
        this.port = port;
    }

    /**
     * Minicat启动需要初始化展开的一些操作
     */
    public void start() throws IOException {
        loadServer();
        int corePoolSize = 10;
        int maximumPoolSize = 50;
        long keepAliveTime = 100L;
        TimeUnit unit = TimeUnit.SECONDS;
        BlockingQueue<Runnable> workQueue = new ArrayBlockingQueue<>(50);
        ThreadFactory threadFactory = Executors.defaultThreadFactory();
        RejectedExecutionHandler handler = new ThreadPoolExecutor.AbortPolicy();
        ThreadPoolExecutor poolExecutor = new ThreadPoolExecutor(corePoolSize, maximumPoolSize,
                keepAliveTime, unit, workQueue, threadFactory, handler);

        ServerSocket serverSocket = new ServerSocket(port);
        System.out.println("======>>>Minicat start on port:" + port);
        //多线程改造（使用线程池）
        while (true) {
            System.out.println("多线程改造");
            Socket socket = serverSocket.accept();
            RequestProcessor requestProcessor = new RequestProcessor(socket, servletMap);
            poolExecutor.execute(requestProcessor);
//            requestProcessor.start();

        }
    }

    private Map<String, HttpServlet> servletMap = new HashMap<>();

    /**
     * 初始化加载server类
     */
    private void loadServer() {
        InputStream inputStream = this.getClass().getClassLoader().getResourceAsStream("server.xml");
        SAXReader saxReader = new SAXReader();
        Document document = null;
        try {
            document = saxReader.read(inputStream);
            Element rootElement = document.getRootElement();
            Element connector = (Element) rootElement.selectSingleNode("//Connector");
            //获取端口号
            port = Integer.parseInt(connector.attributeValue("port"));
            //获取host信息
            List<Host> hosts = loadHost(rootElement);
            //加载servlet
            hosts.forEach(host -> {
                List<Context> contexts = host.getContexts();
                contexts.forEach(context -> {
                    try {
                        loadServlet(context);
                    } catch (IOException e) {
                        e.printStackTrace();
                    }
                });


            });
        } catch (Exception e) {
            e.printStackTrace();
        }
    }

    /**
     * 获取配置host信息
     *
     * @param rootElement
     * @return
     */
    private List<Host> loadHost(Element rootElement) {
        List<Element> hostNodes = rootElement.selectNodes("//Host");
        List<Host> hosts = new ArrayList<>();
        hostNodes.forEach(node -> {
            Host host = new Host();
            host.setName(node.attributeValue("name"));
            host.setAppBase(node.attributeValue("appBase"));
            List<Context> contexts = loadContext(host);
            host.setContexts(contexts);
            hosts.add(host);
        });
        return hosts;
    }

    /**
     * 载入Content信息
     * clsspath如user/taoxiaoyin/webapp/demo1
     *
     * @param host 主机配置信息对象
     * @return
     */
    private List<Context> loadContext(Host host) {
        //获取部署目录
        String appBase = host.getAppBase();
        File file = new File(appBase);
        List<Context> contexts = new ArrayList<>();
        //判断部署目录 是否存在
        if (!file.exists()) {
            System.out.println("部署目录不存在");
            return contexts;
        }
        //判断部署是否为文件夹
        if (!file.isDirectory()) {
            System.out.println("部署目录不是一个有效的文件目录");
            return contexts;
        }
        //获取所有的该文件夹下所有的目录为context
        File[] files = file.listFiles();
        for (File file1 : files) {
            if (file1.isDirectory()) {
                Context context = new Context();
                context.setName(file1.getName());
                context.setPath(file1.getPath());
                contexts.add(context);
            }
        }
        return contexts;

    }

    /**
     * 加载部署目录下web.xml，初始化Servlet
     */
    private void loadServlet(Context context) throws IOException {
        File file = new File(context.getPath() + "/web.xml");
        InputStream inputStream = new FileInputStream(file);
        SAXReader saxReader = new SAXReader();
        Document document = null;
        try {
            document = saxReader.read(inputStream);
            Element rootElement = document.getRootElement();
            List<Element> selectNodes = rootElement.selectNodes("//servlet");
            selectNodes.forEach(selectNode -> {
                Element servletNameElement = (Element) selectNode.selectSingleNode("servlet-name");
                String servletName = servletNameElement.getStringValue();
                Element servletClassElement = (Element) selectNode.selectSingleNode("servlet-class");
                String servletClass = servletClassElement.getStringValue();
                //根据servlet-name找到url-partten
                Element servletMapping = (Element) rootElement.selectSingleNode("/web-app/servlet-mapping[servlet-name='" + servletName + "']");
                String urlPattern = servletMapping.selectSingleNode("url-pattern").getStringValue();
                //根据路径 加载类
                HttpServlet servlet = loadServletClass(context, servletClass);
                servletMap.put("/" + context.getName()+urlPattern, servlet);

            });
        } catch (DocumentException e) {
            e.printStackTrace();
        }

    }

    /**
     * 获取指定目录的servlet类
     *
     * @param context
     * @param servletClass
     * @return
     */
    private HttpServlet loadServletClass(Context context, String servletClass) {
        try {
            //获取servlet全路径
            String path = context.getPath() + "/" + servletClass.replace(".", "/") + ".class";
            //反射生成类对象
            ClassLoader classLoader = new MyClassLoader(path);
            HttpServlet servlet = (HttpServlet) classLoader.loadClass(servletClass).newInstance();
            return servlet;

        } catch (Exception e) {
            e.printStackTrace();
            return null;
        }

    }

    /**
     * Minicat的启动入口
     *
     * @param args
     */
    public static void main(String[] args) {
        Bootstrap bootstrap = new Bootstrap();
        try {
            //启动
            bootstrap.start();
        } catch (IOException e) {
            e.printStackTrace();
        }
    }
}
